package org.xzx.shop_api.controller;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.client.elc.NativeQuery;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.HighlightQuery;
import org.springframework.data.elasticsearch.core.query.highlight.Highlight;
import org.springframework.data.elasticsearch.core.query.highlight.HighlightField;
import org.springframework.data.elasticsearch.core.query.highlight.HighlightParameters;
import org.springframework.web.bind.annotation.*;
import org.xzx.shop_api.entity.ESNews;
import org.xzx.shop_api.entity.News;
import org.xzx.shop_api.utils.JsonResult;
import org.xzx.shop_api.utils.Tool;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/api/news")
public class NewsController {

    @Autowired
    private ElasticsearchOperations elasticsearchOperations; //创建索引
    @GetMapping("create")
    public JsonResult create() {
        IndexOperations indexOperations = elasticsearchOperations.indexOps(ESNews.class);
        if (!indexOperations.exists()) {
            indexOperations.create();
        }
        return JsonResult.success("ok",null);
    }

    //索引文档
    @PostMapping("add")
    public JsonResult add(@RequestBody News news) {
        news.setCreateTime(Tool.getCurrentTime());
        System.out.println(news);
        News result = elasticsearchOperations.save(news);
        if (result == null) {
            return JsonResult.failed("添加失败");
        }
        return JsonResult.success("添加成功",news);
    }


    //根据id查询文档接口
    @GetMapping("/getById")
    public JsonResult getNewsById(@RequestParam String id) {
        if (id == null || id.isEmpty()) {
            return JsonResult.failed("id不能为空");
        }
        News news = elasticsearchOperations.get(id, News.class);
        return JsonResult.success("查询成功",news);
    }



    //10. 根据id删除文档接口

    @PostMapping("/deleteById")
    public JsonResult deleteNewsById(@RequestParam String id) {
        // 先查询是否存在
        News news = elasticsearchOperations.get(id, News.class);
        if (news == null) {
            return JsonResult.failed("文档不存在");
        }
        elasticsearchOperations.delete(id, News.class);
        return JsonResult.success("删除成功",null);

    }


    /*//精确搜索
    @GetMapping("search")
    public JsonResult search(@RequestParam("wd") String wd) {
        if (wd.isEmpty()) {
            //
        }
        System.out.println(wd);
        Criteria criteria = new Criteria("title").contains(wd);
        CriteriaQuery query = new CriteriaQuery(criteria);

        SearchHits<News> hits = elasticsearchOperations.search(query, News.class);
        System.out.println(hits);

        List<News> newsList = hits.stream()
                .map(SearchHit::getContent)
                .toList();
        return JsonResult.success("ok",newsList);
    }
    //ik分词搜索
    @GetMapping("match")
    public JsonResult match(@RequestParam(value = "wd",required = false) String wd) {
        // 如果没有关键词就搜索全部
        try {
            NativeQuery query = NativeQuery.builder()
                    .withQuery(q -> {
                        if (wd == null || wd.trim().isEmpty()) {
                            return q.matchAll(m -> m);
                        } else {
                            return q.match(m -> m.field("title").query(wd));
                        }
                    })
                    .build();
            SearchHits<News> searchHits = elasticsearchOperations.search(query, News.class);
            HashMap<String, Object> resultData = new HashMap<>();
            resultData.put("hits", searchHits.getSearchHits());
            resultData.put("totalHits", searchHits.getTotalHits());
            return JsonResult.success("搜索成功", resultData);
        } catch (Exception e) {
            return JsonResult.failed("搜索失败: " + e.getMessage());
        }
    }
    // 高亮搜索
    @GetMapping("highlight")
    public JsonResult highlight(@RequestParam("wd") String wd) {
        // 创建高亮配置
        HighlightField highlightField = new HighlightField("title");
        HighlightParameters parameters = HighlightParameters.builder()
                .withPreTags("<span style='color: red'>")
                .withPostTags("</span>")
                .withFragmentSize(Integer.MAX_VALUE)
                .withNumberOfFragments(1)
                .build();

        Highlight highlight = new Highlight(parameters, List.of(highlightField));
        HighlightQuery highlightQuery = new HighlightQuery(highlight, News.class);

        // 构建查询
        NativeQuery query = NativeQuery.builder()
                .withQuery(q -> q
                        .match(m -> m
                                .field("title")
                                .query(wd)
                        )
                )
                .withHighlightQuery(highlightQuery)
                .build();
        SearchHits<News> searchHits = elasticsearchOperations.search(query, News.class);
        HashMap<String, Object> resultData = new HashMap<>();
        resultData.put("hits", searchHits.getSearchHits());
        resultData.put("totalHits", searchHits.getTotalHits());
        return JsonResult.success("搜索成功",resultData);
    }*/

    //搜索
    @GetMapping("search")
    public JsonResult search(@RequestParam("title") String title,
                             @RequestParam("create_time") String createtime
    ) {

        // 创建高亮配置
        HighlightField highlightField = new HighlightField("title");
        HighlightParameters parameters = HighlightParameters.builder()
                .withPreTags("<span style='color: red'>")
                .withPostTags("</span>")
                .withFragmentSize(Integer.MAX_VALUE)
                .withNumberOfFragments(1)
                .build();


        Highlight highlight = new Highlight(parameters, List.of(highlightField));
        HighlightQuery highlightQuery = new HighlightQuery(highlight, News.class);


        NativeQuery query;
        if (StringUtils.isNotBlank(title)) {
            // 有关键字
            query = NativeQuery.builder()
                    .withQuery(q -> q.match(m -> m.field("title").query(title)))
                    .withHighlightQuery(highlightQuery)
                    .withPageable(PageRequest.of(0, 10, Sort.by(Sort.Order.desc("create_time"))))
                    .build();
        } else {
            // 无关键字：查询全部新闻
            query = NativeQuery.builder()
                    .withQuery(q -> q.matchAll(m -> m)) // 匹配所有数据
                    .withPageable(PageRequest.of(0, 10, Sort.by(Sort.Order.desc("create_time"))))
                    .build();
        }

        SearchHits<News> searchHits = elasticsearchOperations.search(query, News.class);
        HashMap<String, Object> resultData = new HashMap<>();
        resultData.put("hits", searchHits.getSearchHits());
        resultData.put("totalHits", searchHits.getTotalHits());
        return JsonResult.success("搜索成功",resultData);
    }
}